package com.chat.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bean.Message;

/**
 * @author pjt
 * 
 */
public class Server extends HttpServlet {

	public Server() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/*
	 * 此方法用于用户登陆
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();

		String _ip = getIpAddr(request);
		System.out.println("远程IP：" + _ip);
		if (!lineIPS.contains(_ip)) {
			lineIPS.add(_ip);
		}
		String lineUsers = null;
		if (lineIPS.size() > 0) {
			lineUsers = "[";
			Iterator<String> eip = lineIPS.iterator();
			String ip = null;
			while (eip.hasNext()) {
				ip = eip.next();
				lineUsers += "{text:'"
						+ (_ip.equals(ip) ? "自己(" + ip + ')' : ip)
						+ "',leaf:true,id:'" + ip + "'},";
			}
			lineUsers = lineUsers.substring(0, lineUsers.length() - 1);
			lineUsers += "]";
		}
		System.out.println(lineUsers);
		// 发送JSON数据
		out.write(lineUsers);
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		// PrintWriter out = response.getWriter();
		// String _reciveMsg = request.getParameter("msg");
		// String _targetip = request.getParameter("ip");
		// String _ip = request.getRemoteAddr();
		// System.out.println("客户" + _ip + "发送聊天内容：" + _reciveMsg + "到："
		// + _targetip);
		// String sendMsg = "{result:succse}";
		// out.write(sendMsg);
		// out.flush();
		// out.close();
		this.currentvisitors = request.getRemoteAddr();
		String action = request.getParameter("action");
		// 客户端如果是发送消息
		// 服务器端就是接收消息 否则相反
		if ("reciveMsg".equals(action)) {
			sendMsg(request, response);
		} else if ("sendMsg".equals(action)) {
			receiveMsg(request);
		}
	}

	private Map<String, List<Message>> msgs;

	private Set<String> lineIPS;

	private String currentvisitors;

	public void init() throws ServletException {
		msgs = new HashMap<String, List<Message>>();

		lineIPS = new HashSet<String>();
	}

	private void receiveMsg(HttpServletRequest request) throws ServletException,
			IOException {
		String _msg = request.getParameter("msg");
		String _receiver = request.getParameter("receiver");
		String _sender = this.currentvisitors;
		System.out.println("接收客户端发送过来的消息：" + _msg);
		List<Message> _receiverMsgs = null;
		if (null == (_receiverMsgs = msgs.get(_receiver))) {
			_receiverMsgs = new ArrayList<Message>();
			msgs.put(_receiver, _receiverMsgs);
		}
		Message _reciveerMsg = new Message();
		_reciveerMsg.setSender(_sender);
		_reciveerMsg.setReceiver(_receiver);
		_reciveerMsg.setMsg(_msg);
		_receiverMsgs.add(_reciveerMsg);
	}

	private void sendMsg(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String _sender = request.getParameter("sender");
		// 发送消息
		List<Message> _receiverMsgs = msgs.get(this.currentvisitors);
		if (null == _receiverMsgs || _receiverMsgs.isEmpty())
			return;
		Iterator<Message> ite = _receiverMsgs.iterator();
		Message msg;
		String result = "{msgs:[";
		while (ite.hasNext()) {
			msg = ite.next();
			if (_sender.equals(msg.getSender())) {
				result += "{sender:'" + msg.getSender() + "',msg:'"
						+ msg.getMsg() + "'},";
				ite.remove();
				System.out.println("移除后的：" + _receiverMsgs);
			}
		}
		result = result.substring(0, result.length() - 1) + "]}";
		System.out.println("发送消息：" + result);
		out.write(result);
		out.flush();
		out.close();

		// 清除针对当前IP消息对象
		if (_receiverMsgs.isEmpty()) {
			msgs.remove(this.currentvisitors);
		}
	}
	
	/**获取主机的真实IP
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) 
	{    
	    String ip = request.getHeader("x-forwarded-for");    
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) 
	    {    
	        ip = request.getHeader("Proxy-Client-IP");    
	    }    
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) 
	    {    
	        ip = request.getHeader("WL-Proxy-Client-IP");    
	    }    
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) 
	    {    
	        ip = request.getRemoteAddr();    
	    }    
	    return ip;    
	}
}
